<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">

								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-cell icon="calendar" size="large">
											<view slot="title" class="u-slot-title">
												<text class="u-cell-text u-cell_text">申请人填写</text>
											</view>
										</u-cell>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="单据编号:" required>
											<u--input v-model="baseFormData.BillNO" placeholder="自动生成单据编号" readonly
												border="none"></u--input>
										</u-form-item>

									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="单据日期:">
											<u--input v-model="baseFormData.BillDate" placeholder="自动生成单据日期" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验类型:" required
											@click="openBaseScreen('检验类型')">
											<u--input v-model="baseFormData.InspectionTypeName" readonly
												placeholder="请选择异常原因" border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="派工单编号:">
											<u--input v-model="baseFormData.PGBillNo" placeholder="自动带出派工单编号" readonly
												border="none"></u--input>
										</u-form-item>

									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="产品名称:">
											<u--input v-model="baseFormData.ProductName" placeholder="自动带出产品名称" readonly
												border="none"></u--input>
										</u-form-item>

									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="产品检验单号:">
											<u--input v-model="baseFormData.JYBillNo" placeholder="自动带出检验单号" readonly
												border="none"></u--input>
										</u-form-item>

									</u-col>
								</u-row>
								<u-row justify="start" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="送检数量:" required>
											<u--input v-model="baseFormData.CkAmount" type="number"
												placeholder="请输入送检数量" border="none"></u--input>
										</u-form-item>

									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="申请人:">
											<u--input v-model="baseFormData.Declarer" placeholder="自动带出申请人" readonly
												border="none"></u--input>
										</u-form-item>

									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="抽样次数:" required>
											<u--input v-model="baseFormData.SamplingCount" placeholder="请输入抽样次数"
												type="number" border="none"></u--input>
										</u-form-item>

									</u-col>
								</u-row>

								<u-row justify="start" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="抽样数量:" required>
											<u--input v-model="baseFormData.SamplingAmount"
												@blur='ChangeSamplingAmount("抽样数量")' placeholder="请输入抽样数量" type="number"
												border="none"></u--input>
										</u-form-item>

									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="抽样合格数量:" required>
											<u--input v-model="baseFormData.SamplingOKAmount" placeholder="请输入抽样合格数量"
												@blur='ChangeSamplingAmount("合格数量")' type="number"
												border="none"></u--input>
										</u-form-item>

									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="抽样不合格数量:" required>
											<u--input v-model="baseFormData.SamplingBadAmount" placeholder="请输入抽样不合格数量"
												@blur='ChangeSamplingAmount("不合格数量")' type="number"
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="8">
										<u-form-item labelWidth="auto" label="异常描述:" required>
											<u--input v-model="baseFormData.GZContent" placeholder="请输入异常描述"
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-form-item labelWidth="auto" label="现场照片:">
											<u-upload :fileList="DImgs" @afterRead="afterRead" @delete="deletePic"
												multiple :maxCount="5" :previewFullImage="true"></u-upload>
										</u-form-item>
									</u-col>

								</u-row>
							</u--form>

						</view>

					</view>

					<view class="DetailsbottomBtns">

						<button class="button1" block @click="submit" style="z-index: 99;">
							{{changeButton}}
						</button>
						<button class="button2" block @click="devicerepair" v-show="titleShow">
							评审单
						</button>
					</view>

				</view>
			</template>

		</st-mc-framework>
		<u-datetime-picker :show="show" v-model="value1" mode="date" @cancel='show=false'
			@confirm='pickerConfirm'></u-datetime-picker>


		<u-action-sheet :actions="showNameList" :show="showName" @select="addName"
			@close="showName=false"></u-action-sheet>

		<u-toast ref="uToast"></u-toast>

		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm' :showCancelButton='true'
			@cancel='modalshow=false'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>


	</view>
</template>

<script>
	import {
		getFormatDate,
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {

				DImgs: [],
				serverIP: '',

				baseFormData: {
					FaultTypeID: null,
					JYBillNo: '',
					InspectionID: null,
					FType: "",
					BillNO: "",
					PGBillNo: "",
					CkAmount: null,
					ProductID: null,
					ProductName: "",
					InspectionType: null,
					InspectionTypeName: '',
					BillDate: '',
					Declarer: '',
					SamplingCount: '',
					SamplingAmount: '',
					SamplingOKAmount: '',
					SamplingBadAmount: 0,
					GZContent: '',

					DeclarerID: null,
					EquipmentName: '',
					EquipmentCode: '',
					EquipmentID: null,
					JobOrderID: null,

				},
				DImgs: [],
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],
				TimeName: '',
				show: false,
				value1: Number(new Date()),
				showName: false,
				showNameList: [],
				changeName: '',
				changeButton: '保存',
				titleShow: false,
				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',
			};
		},
		mounted() {},
		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				console.log(res.data);
				this.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			console.log(that.FWorkshopID);
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName;
			console.log(that.ModuleTitle);
			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(onLoad) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			var Detailsitem = JSON.parse(onLoad.item)
			// 主处理逻辑
			if (Detailsitem.FaultDocID) {
				setLoading(true);
				that.queryList(Detailsitem.FaultDocID)
				return;
			}
			delete Detailsitem.BillNO; // 删除obj对象的age属性
			// 统一处理表单默认值
			var formDefaultsInfo = {
				...Detailsitem,
				Declarer: UserInfo.EmplName,
				DeclarerID: UserInfo.EmplID,
				EquipmentName: MesBasicInfo.warehouse.EquipmentName,
				EquipmentCode: MesBasicInfo.warehouse.EquipmentCode,
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,
				BillDate: getFormatDate(new Date())
			};

			var formDefaultsobj = {
				...formDefaultsInfo,
			};
			console.log(formDefaultsInfo);
			switch (formDefaultsInfo.FaultTypeID) {
				case 1:
					formDefaultsobj.FaultTypeName = '设备异常'
					break;
				case 2:
					formDefaultsobj.FaultTypeName = '模具异常'
					break;
				case 3:
					formDefaultsobj.FaultTypeName = '工艺异常'
					break;
				default:
					break;
			}
			console.log(formDefaultsobj);
			this.assignFormData(this.baseFormData, formDefaultsobj);

			if (that.baseFormData.FType == 'SJJ' || that.baseFormData.FType == 'ZJ') {
				this.assignFormData(this.baseFormData, {
					FaultTypeID: 4,
					FaultTypeName: '品质异常'
				});
			}
			setLoading(false);

			this.addgetInspectionType()
		},

		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		methods: {
			devicerepair() {
				let that = this;
				that.showModal('提醒', '是否跳转评审单');

			},
			GonavigateTo(obj, url) {
				let that = this;
				this.$safeNavigate({
					targetUrl: url, // 目标页面路径
					payload: obj, // 要传递的数据
				});
			},
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
				if (that.modaltitle == '提醒') {
					let url
					let routes = getCurrentPages();
					if (that.baseFormData.FaultDocID) {
						var initData = JSON.parse(JSON.stringify(that.$store.state.GuyueModule.ModuleData_select));
						var parentData = initData[initData.length - 1]
						parentData.url = `/st_mes_zs/abnormal/qualityDetails?FaultDocID=${that.baseFormData.FaultDocID}`
						that.$modifyParentData(parentData);
					}
					let obj = {
						path: 'manual',
						length: routes.length + 1
					}
					var item = {
						BillNO: that.baseFormData.BillNO,
						BillDate: that.baseFormData.BillDate,
						PGDBillNO: that.baseFormData.PGBillNo,
						InspectionID: that.baseFormData.Source,
						ProductID: that.baseFormData.ProductID,
						ProductName: that.baseFormData.ProductName,
						EquipmentName: that.baseFormData.EquipmentName,
						EquipmentID: that.baseFormData.EquipmentID,
						EmplName: that.baseFormData.Declarer ? that.baseFormData.Declarer : that.$store.state.UserInfo
							.EmplName,
						EmplID: that.baseFormData.DeclarerID ? that.baseFormData.DeclarerID : that.$store.state
							.UserInfo
							.EmplID,
					}
					url = `/st_mes_zs/abnormal/materialreviewDetail?Detailsitem=${JSON.stringify(item)}`
					obj = {
						...obj,
						Name: '物料评审详情',
						APPFunID: '物料评审详情',
						url: url
					}
					console.log(obj);
					this.GonavigateTo(obj, url)
				}
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			UpdateAssignFormData(formDefaults) {
				this.assignFormData(this.baseFormData, formDefaults)
			},
			ChangeSamplingAmount(str, event) {
				var that = this
				console.log(event);
				const {
					SamplingAmount,
					SamplingOKAmount,
					SamplingBadAmount,
				} = that.baseFormData;
				var formDefaults = {}
				switch (str) {
					case '抽样数量':
						if (SamplingAmount < 0) {
							that.showModal('提示', '抽样数量不能小于0');
							formDefaults = {
								SamplingAmount: 0,
								SamplingOKAmount: 0,
								SamplingBadAmount: 0
							};
						} else {
							formDefaults = {
								SamplingOKAmount: SamplingAmount,
								SamplingBadAmount: 0
							};
						}
						break;
					case '合格数量':
						if (SamplingOKAmount >= 0) {
							if (Number(SamplingAmount) >= Number(SamplingOKAmount)) {
								formDefaults = {
									SamplingBadAmount: Number(SamplingAmount) - Number(SamplingOKAmount)
								};
							} else {
								if (SamplingOKAmount) {
									that.showModal('提示', '合格数量不能大于抽样数量');
								}
								formDefaults = {
									SamplingOKAmount: 0,
									SamplingBadAmount: SamplingAmount
								};

							}
						} else if (SamplingOKAmount < 0) {
							that.showModal('提示', '合格数量不能小于0');
							formDefaults = {
								SamplingOKAmount: 0,
								SamplingBadAmount: SamplingAmount
							};
						}
						break;
					case '不合格数量':
						if (SamplingBadAmount >= 0) {
							if (Number(SamplingAmount) >= Number(SamplingBadAmount)) {
								formDefaults = {
									SamplingOKAmount: Number(SamplingAmount) - Number(SamplingBadAmount)
								};
							} else {
								if (SamplingBadAmount) {
									that.showModal('提示', '不合格数量不能大于抽样数量');
								}
								formDefaults = {
									SamplingBadAmount: 0,
									SamplingOKAmount: SamplingAmount
								};

							}
						} else if (SamplingBadAmount < 0) {
							that.showModal('提示', '不合格数量不能小于0');
							formDefaults = {
								SamplingBadAmount: 0,
								SamplingOKAmount: SamplingAmount
							};
						}
						break;
				}
				that.UpdateAssignFormData(formDefaults)

			},
			deletePic(event) {
				this.DImgs.splice(event.index, 1);
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				console.log(event);
				let fileListLen = this.DImgs.length;
				lists.map((item) => {
					this.DImgs.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.DImgs[fileListLen]
					this.DImgs.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: this.Request.IPAgreement() + this.Request.serverIP() + result
					}))
					fileListLen++
				}
			},

			uploadFilePromise(url) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: that.Request.IPAgreement() + that.Request
							.serverIP() + '/Frame/uploadFile?dirName=' + '异常现场',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data' // 必须设置
						},
						formData: {
							user: 'test'
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							// console.log(data);
							resolve(data.data)
						}
					});
				})
			},


			addgetInspectionType(str) {
				let that = this;
				console.log(that.baseFormData.InspectionID);
				that.Request.request('getInspectionDetail', {
					InspectionID: that.baseFormData.InspectionID
				}, (ret) => {
					console.log(ret)
					const formDefaults = {
						FType: ret.data?.ds?.[0]?.FType ? ret.data?.ds?.[0]?.FType : '',
						JYBillNo: ret.data?.ds?.[0]?.BillNO ? ret.data?.ds?.[0]?.BillNO : '',
					};
					that.assignFormData(that.baseFormData, formDefaults)
					if (that.baseFormData.FType) {
						that.Request.request('getInspectionType', {
							ID: that.baseFormData.FType ? that.baseFormData.FType : ''
						}, (ret) => {
							console.log(JSON.stringify(ret))
							if (ret.status == 200 && ret.data.ds.length > 0) {
								const formDefaults = {
									InspectionType: ret.data.ds[0].NAME,
								};
								that.assignFormData(that.baseFormData, formDefaults)
							}
						})
					}
				})

			},

			openBaseScreen(str) {
				var that = this;
				var obj;
				if (str == '检验类型') {
					obj = {
						cmd: 'getInspectionType',
						type: str,
						serverSearch: {
							isPaging: false, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'NAME', //搜索关键词，应包含在param中
							showText: 'NAME', //查询结果显示的字段
						},
						param: {
							ID: that.baseFormData.FType ? that.baseFormData.FType : '',
							PageIndex: 1,
							PageSize: 30
						}
					}
					console.log(obj);
					uni.navigateTo({
						url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
						animationType: 'slide-in-right',
						animationDuration: 300
					});
				}

			},
			getValue(payload) {
				var that = this;
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'检验类型': () => ({
						InspectionType: data.ID,
						InspectionTypeName: data.NAME
					})


				};
				if (typeHandlers[type]) {
					Object.assign(this.baseFormData, typeHandlers[type]());
				}
			},

			addName(e) {
				var that = this
				console.log(e);
				const formDefaults = {
					QCEmplID: e.EmplID,
					QCEmplName: e.EmplName,
				};
				that.assignFormData(that.baseFormData, formDefaults)


				that.showName = false

			},

			changebuttons(ID) {
				if (ID == 0) {
					this.changeButton = '开工'
				} else {
					this.changeButton = '保存'

				}
			},


			// 获取时间
			pickerConfirm(e) {
				var that = this;
				var time = getFormatDateTime(e.value)
				const formDefaults = {
					BillDate: time,
				};
				that.assignFormData(that.baseFormData, formDefaults)

				this.show = false

			},

			// 保存
			submit() {
				var that = this;
				var show = true
				var msg
				console.log(this.baseFormData);

				if (that.baseFormData.InspectionType == '' || that.baseFormData.InspectionType == null) {
					msg = '请输入检验类型'
					show = false
				} else if (that.baseFormData.CkAmount == '' || that.baseFormData.CkAmount == null) {
					msg = '请输入送检数量'
					show = false
				} else if (that.baseFormData.SamplingCount == '' || that.baseFormData.SamplingCount == null) {
					msg = '请输入抽样次数'
					show = false
				} else if (that.baseFormData.SamplingAmount == '' || that.baseFormData.SamplingAmount == null) {
					msg = '请输入抽样数量'
					show = false
				} else if (that.baseFormData.SamplingOKAmount == '' || that.baseFormData.SamplingOKAmount == null) {
					msg = '请输入抽样合格数量'
					show = false
				}
				// else if (that.baseFormData.SamplingBadAmount == '' || that.baseFormData.SamplingBadAmount == null) {
				// 	msg = '请输入抽样不合格数量'
				// 	show = false
				// } 
				else if (that.baseFormData.GZContent == '' || that.baseFormData.GZContent == null) {
					msg = '请输入异常描述'
					show = false
				}
				if (show) {
					const prefix = that.Request.IPAgreement() + that.Request.serverIP();
					console.log(that.DImgs);
					that.DImgs.map(obj => {
						if (typeof obj.url === 'string' && obj.url.startsWith(prefix)) {
							obj.url = obj.url.replace(prefix, '');
						}
						return obj;
					});
					console.log(that.DImgs);
					var obj = {

						JobOrderID: that.baseFormData.JobOrderID,
						BillDate: that.baseFormData.BillDate,
						InspectionType: that.baseFormData.InspectionType,
						ProductID: that.baseFormData.ProductID,
						ProductName: that.baseFormData.ProductName,
						CkAmount: that.baseFormData.CkAmount,
						Declarer: that.baseFormData.Declarer,
						SamplingCount: that.baseFormData.SamplingCount,
						SamplingAmount: that.baseFormData.SamplingAmount,
						SamplingOKAmount: that.baseFormData.SamplingOKAmount ? that.baseFormData.SamplingOKAmount : 0,
						SamplingBadAmount: that.baseFormData.SamplingBadAmount ? that.baseFormData.SamplingBadAmount :
							0,
						GZContent: that.baseFormData.GZContent,
						FilePath1: that.DImgs.map(item => item.url).join(','),
						FaultDocID: that.baseFormData.FaultDocID ? that.baseFormData.FaultDocID : 0,
						BillType: 'PZYC',
						Source: that.baseFormData.InspectionID,
						FWorkShopID: that.FWorkshopID,
						EquipmentID: that.baseFormData.EquipmentID,
						FaultTypeID: that.baseFormData.FaultTypeID
					}
					console.log(obj);
					that.Request.request('saveFaultDoc', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							setTimeout(() => {
								that.queryList(ret.data.ds[0].FaultDocID)
							}, 1000)
						}
					})

				} else {
					that.showModal('报错', msg);
				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getFaultDocDetail', {
						FaultDocID: id
					}, (ret) => {
						that.showMLoading = false
						console.log(ret.data);
						const [firstItem] = ret.data.ds;
						var stringArray = firstItem.FilePath1.split(',')
						if (stringArray[0] != '' && stringArray.length > 0) {
							that.DImgs = stringArray.map(item => ({
								url: that.Request.IPAgreement() + that.Request.serverIP() + item.trim()
							}));
						}
						const formDefaults = {
							...firstItem,
							BillNO: firstItem.BillNo,
							BillDate: formatDateTime(firstItem.BillDate)
						};
						that.assignFormData(that.baseFormData, formDefaults)
						if (that.baseFormData.FaultDocID) {
							that.titleShow = true
						}
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					that.showMLoading = false
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},

		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.u_form .u-cell__body {
		padding: 5px 0 !important;

		.u-cell_text {
			font-weight: 600 !important;
		}
	}

	.form-item-row {
		display: flex;
		flex-wrap: wrap;

		.uni-forms-item {
			width: 46%;
			margin: 0.3% 2%;

			input {
				height: 100%;
				width: 34vw;
				border-bottom: 2px solid #51d0d0;
			}
		}

		.uni_forms_item {
			width: 100%;
			display: flex;
			align-items: center;

			.u-upload {
				width: 83vw;
				float: right;
			}

			// ::v-deep.u-icon__icon {
			// 	font-size: 20rpx !important;
			// }
		}

	}

</style>